package org.xxpay.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.entity.MchAccountHistory;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.service.IXxPayNotifyService;
import org.xxpay.pay.mq.BaseNotify4MchPay;
import org.xxpay.pay.mq.MchNotifyBean;
import org.xxpay.pay.mq.queue.MqQueue4Statistics;
import org.xxpay.pay.service.CommonService;

/**
 * @author: dingzhiwei
 * @date: 2018/5/29
 * @description:
 */
@Service(interfaceName = "org.xxpay.core.service.IXxPayNotifyService", version = Constant.XXPAY_SERVICE_VERSION, retries = Constant.DUBBO_RETRIES)
public class XxPayNotifyServiceImpl implements IXxPayNotifyService {

    private static final MyLog _log = MyLog.getLog(XxPayNotifyServiceImpl.class);

    @Autowired
    private CommonService commonService;

	@Autowired
	public BaseNotify4MchPay baseNotify4MchPay;

	@Autowired
	private MqQueue4Statistics mqQueue4Statistics;
    
	/**
	 * 发送支付订单通知
	 * @param payOrderId
	 */
	public void executePayNotify(String payOrderId) {
		_log.info(">>>>>> 调取rpc补发支付通知,payOrderId：{}", payOrderId);
		PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
		baseNotify4MchPay.doNotify(payOrder, true);
		_log.info(">>>>>> 调取rpc补发支付通知完成  <<<<<<");
	}

	@Override
	public JSONObject manualPayNotify(PayOrder payOrder, String notifyUrl) {
		try {
			if (StringUtils.isNotEmpty(notifyUrl)) {
				payOrder.setNotifyUrl(notifyUrl);
			}
			// 获取通知路径
            MchNotifyBean mchNotifyBean = baseNotify4MchPay.createMchNotifyBean(payOrder, "2", true);
            // 返回回调信息
            String result = XXPayUtil.call4PostNotify(mchNotifyBean.getNotifyUrl());
            JSONObject json = new JSONObject();
            json.put("notifyUrl", mchNotifyBean.getNotifyUrl());
            json.put("signStr", mchNotifyBean.getSignStr());
            json.put("sign", mchNotifyBean.getSign());
            json.put("result", result);
            return json;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void sendRechargeStatisticsSuccess(MchAccountHistory record, Byte rechargeType) {
		mqQueue4Statistics.sendRechargeStatisticsSuccess(record, rechargeType);
	}

	@Override
	public void sendPayStatistics(String payOrderId, Long diffAmount) {
		_log.info(">>>>>> 调取rpc补发支付统计通知,payOrderId：{}", payOrderId);
		PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
		mqQueue4Statistics.sendPayStatistics(payOrder, MchConstant.ORDER_STATUS_SUCCESS, diffAmount);
		_log.info(">>>>>> 调取rpc补发支付统计通知完成  <<<<<<");
	}


}
